using System.Text.Json;
using Mathmall.Administration.Mapper;
using Mathmall.Administration.Models;
using Mathmall.Administration.Vo;

namespace Mathmall.Administration.Service.impl;

public class MenuService : IMenuService
{
    private readonly MenuMapper _menuMapper;

    public MenuService(MenuMapper menuMapper)
    {
        _menuMapper = menuMapper;
    }


    /// <summary>
    /// 添加菜单
    /// </summary>
    /// <param name="menuVo"></param>
    /// <returns></returns>
    public async Task<int> AddMenu(MenuVo menuVo)
    {
        Menu menu = JsonSerializer.Deserialize<Menu>(JsonSerializer.Serialize(menuVo))!;
        return await _menuMapper.CreateMenu(menu);
    }

    public async Task<List<MenuVo>> GetMenus()
    {
        List<Menu> menus = await _menuMapper.GetMenus();
        List<MenuVo> menuVoList = JsonSerializer.Deserialize<List<MenuVo>>(JsonSerializer.Serialize(menus))!;
        return BuildMenuVos(menuVoList);
    }

    /// <summary>
    /// 更新菜单
    /// </summary>
    /// <param name="menuVo"></param>
    /// <returns></returns>
    public async Task<int> UpdateMenu(MenuVo menuVo)
    {
        Menu menu = JsonSerializer.Deserialize<Menu>(JsonSerializer.Serialize(menuVo))!;
        return await _menuMapper.UpdateMenu(menu);
    }

    public List<MenuVo> BuildMenuVos(List<MenuVo> menuVoList)
    {
        // 最终返回值
        List<MenuVo> finalNode = new List<MenuVo>();
        // 遍历菜单集合，得到顶级菜单
        foreach (MenuVo menuVo in menuVoList)
        {
            if (0.Equals(menuVo.ParentId))
            {
                // 根据顶级菜单递归查询子菜单
                finalNode.Add(SelectChildren(menuVo, menuVoList));
            }
        }

        return finalNode;
    }

    private MenuVo SelectChildren(MenuVo parentVo, List<MenuVo> menuVoList)
    {
        foreach (MenuVo menuVo in menuVoList)
        {
            // 根据父菜单查询子菜单
            if (parentVo.MenuID.Equals(menuVo.ParentId))
            {
                parentVo.Children.Add(SelectChildren(menuVo, menuVoList));
            }
        }

        return parentVo;
    }

    /// <summary>
    /// 删除菜单
    /// </summary>
    /// <param name="menuID"></param>
    /// <returns></returns>
    public async Task<int> DeleteMenu(int menuID)
    {
        return await _menuMapper.DeleteMenu(menuID);
    }
}